package guoanmaker.operator.business.service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.servlet.http.HttpServletRequest;
import javax.transaction.Transactional;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;

import guoanmaker.operator.business.model.MessageType;
import guoanmaker.operator.business.model.OperatorCity;
import guoanmaker.operator.business.model.OperatorRefuseRecord;
import guoanmaker.operator.business.model.OperatorServerClass;
import guoanmaker.operator.business.model.OperatorStoredataChange;
import guoanmaker.operator.business.model.OperatorUser;
import guoanmaker.operator.business.model.ProvideCity;
import guoanmaker.operator.business.model.ProvideCommodityServiceRange;
import guoanmaker.operator.business.model.ProvideShop;
import guoanmaker.operator.business.model.Provideinfos;
import guoanmaker.operator.business.model.ProviderBusiness;
import guoanmaker.operator.business.model.ReturnResult;
import guoanmaker.operator.business.modelnobind.BusinessRo;
import guoanmaker.operator.business.modelnobind.ProvideCommodityRo;
import guoanmaker.operator.business.modelnobind.ProvideshopRo;
import guoanmaker.operator.business.modelnobind.ShopInfosAudit;
import guoanmaker.operator.business.repository.MessageTypeRepository;
import guoanmaker.operator.business.repository.OperatorCityRepository;
import guoanmaker.operator.business.repository.OperatorRefuseRecordRepository;
import guoanmaker.operator.business.repository.OperatorServerClassRepository;
import guoanmaker.operator.business.repository.OperatorStoredataChangeRepository;
import guoanmaker.operator.business.repository.OperatorUserRepository;
import guoanmaker.operator.business.repository.ProvideAreaRepository;
import guoanmaker.operator.business.repository.ProvideCityRepository;
import guoanmaker.operator.business.repository.ProvideCommodityRepository;
import guoanmaker.operator.business.repository.ProvideCommodityServiceRangeRepository;
import guoanmaker.operator.business.repository.ProvideShopRepository;
import guoanmaker.operator.business.repository.ProviderBusinessRepository;
import guoanmaker.operator.business.repository.ProviderProvinceRepository;
import guoanmaker.operator.helper.common.util.HttpGetUtil;

@Service
public class StoreManageService {
	
	
	@Autowired
	private HttpServletRequest request;
	
	
	@Autowired
	private ProvideCityRepository provideCityRepository;
	
	@Autowired
	private ProvideAreaRepository provideAreaRepository;
	
	@Autowired
	private ProviderProvinceRepository  providerProvinceRepository;
	
	@Autowired
	private OperatorServerClassRepository   operatorServerClassRepository;
	
	@Autowired
	private ProviderBusinessRepository providerBusinessRepository;
	
	@Autowired
	private ProvideShopRepository provideShopRepository;
	
	@Autowired
	private ProvideCommodityRepository provideCommodityRepository;
	
	@Autowired
	private OperatorCityRepository operatorCityRepository;
	
	@Autowired
	private  OperatorUserRepository operatorUserRepository;
	
	@Autowired
	private OperatorRefuseRecordRepository operatorRefuseRecordRepository;
	
	
	
	@Autowired
	private MessageTypeRepository  messageTypeRepository;
	
	@Autowired
	private ProvideCommodityServiceRangeRepository provideCommodityServiceRangeRepository;
	@PersistenceContext
	private EntityManager manager;
	
	
	@Autowired
	private OperatorStoredataChangeRepository  operatorStoredataChangeRepository;
	
	public List<OperatorServerClass> selectById(String pids) {
		List<OperatorServerClass> lists = null;
		if (StringUtils.isNotEmpty(pids)) {
			if (!pids.equals("")) {
				String[] commoditySs = pids.split(",");
				@SuppressWarnings("rawtypes")
				List twoIdList = new ArrayList();
				Collections.addAll(twoIdList, commoditySs);
				lists = operatorServerClassRepository.findByIdIn(twoIdList);
			}
		}
		return lists;
	}
	
	
	/**
	 * 
	 * @param page
	 *            默认为0
	 * @param size
	 *            每页10条
	 * @param status
	 *            状态 (所有，正常，冻结)
	 * @param serverclass
	 *            服务种类
	 * @return
	 */
	public Map<String, Object> selectByAccountforStore(Integer page, Integer size, String serverclass,String companyName,String serverZone) {
     String jpql="select o from Provideinfos o where 1=1";	
        if(StringUtils.isNotEmpty(companyName)){
			jpql+=" and o.businessname like '%"+companyName+"%'";
		}
        if(StringUtils.isNotEmpty(serverclass)){
        	jpql+=" and o.commoditys like '%"+serverclass+"%'";
		}
        if(StringUtils.isNotEmpty(serverZone)){
        	jpql+=" and o.serviceAreas like '%"+serverZone+"%'";
        }
        if(page==null){
			page=0;
		}
		if (size==null) {
			size=10;
		}
		Query query = manager.createQuery(jpql);
		List<Provideinfos> result = query.getResultList();
		Map<String,Object>  map=new HashMap<>();
		map.put("total", result.size());
		query.setFirstResult(page*size);
		query.setMaxResults(size);
		List<Provideinfos> result1 = query.getResultList();
		if(result1.size()>0){
			for (Provideinfos provideinfos : result1) {
				String str = provideinfos.getCommoditys();
				if(str!=null&&!str.equals("")){
					String servername = "";
	    			List<OperatorServerClass> servers=	selectById(str);
	    			if(servers.size()>0&&servers!=null){
	    				for (OperatorServerClass operatorServerClass : servers) {
	    					servername += operatorServerClass.getServerName()+",";
	    				}
	    			}
	    			if(servers==null){
	    				 servername = "";
	    			}
	    			provideinfos.setCommoditys(servername);
				}
				if(provideinfos.getCompanyCity()!=null){
 					List<ProvideCity> provideCitys	= provideCityRepository.findByCode(provideinfos.getCompanyCity());
 					if(provideCitys.size()>0){
 						provideinfos.setCompanyCity(provideCitys.get(0).getName());
 					}
 				}
				provideinfos.setSumscore(getProvideShopScore(provideinfos.getId()));
			}
		}
		map.put("businessInfos", result1);
		return map;
	}
	
	public String getProvideShopScore(String businessId) {

	    String sql = "select avg(a.average_value) from t_personal_appraise a, t_provide_commodity b where a.is_show='1' and a.commodity_id=b.id  and b.business_id='" + businessId + "'";
	    Query navQry = manager.createNativeQuery(sql);
	    if (navQry.getResultList().get(0) == null) {
	        return "暂无评分";
	    }
	    Double score = Double.parseDouble(navQry.getResultList().get(0) + "");
	    String format = String.format("%.1f", score);
	    return format;
	}
	
	
	
   //服务地区下拉展示	
	public   List<String>  selectByServiceZone(){
		 List<String>  arr=new ArrayList<>();
		 List<OperatorCity> ops=	operatorCityRepository.findAll();
			 if(ops.size()>0){
				 for (OperatorCity operatorCity : ops) {
					 List<ProvideCity>  provideCity1=provideCityRepository.findByCode(operatorCity.getCityId());
					 String servercity1="";
					 if(provideCity1.size()>0){
						 servercity1=provideCity1.get(0).getName();
						 arr.add(servercity1);
					 }
				 }
			 }
		return arr;
		
	}
	
	//更新服务商来源
	@Transactional
	public ReturnResult  updateSouceServiceProvide(String id,String sourceName) throws UnsupportedEncodingException{
		ReturnResult  returnResult=new ReturnResult();
		ProviderBusiness providerBusiness=	providerBusinessRepository.findOne(id);
		if(providerBusiness!=null){
			providerBusiness.setSourceProvider(sourceName);
			providerBusinessRepository.save(providerBusiness);
			if((providerBusiness.getCompanyName()!=null&&!providerBusiness.getCompanyName().equals(""))
					||(providerBusiness.getBusinessName()!=null&&!providerBusiness.getBusinessName().equals(""))){
				// 平台描述为10
				String flag = validateBusiness1(10, providerBusiness.getBusinessName(),
						providerBusiness.getCompanyName(), id,sourceName);
				if (flag.equals("SUCCESS")) {
					System.out.println("编辑成功");
				}
			}
			returnResult.setKey("success");
			returnResult.setValue("保存成功");
		}else{
			returnResult.setKey("error");
			returnResult.setValue("保存失败");
		}
		return returnResult;
	}
	
	/**
	 * 调外部编辑接口
	 * 
	 * @param systemCode
	 *            平台描述
	 * @param companyName
	 *            服务商名称
	 * @param companyTitle
	 *            服务商公司名称
	 * @param originalId
	 *            服务商主键Id
	 *            
	 * @return
	 * @throws UnsupportedEncodingException 
	 */
	public static String validateBusiness1(Integer systemCode, String companyName, String companyTitle,
			String originalId,String sourceProvider) throws UnsupportedEncodingException {
		String a = "https://tpay.gack.citic/add_update/company?"+"systemCode=10";
		String b ="&companyName=" + URLEncoder.encode(companyName,"utf-8") + "&companyTitle=" + URLEncoder.encode(companyTitle,"utf-8") + "&originalId=" + URLEncoder.encode(originalId,"utf-8")+"&sourceProvider=" + URLEncoder.encode(sourceProvider,"utf-8");
		String	oinfoma = HttpGetUtil.httpGet(a+b);
		System.out.println(oinfoma);
		com.alibaba.fastjson.JSONObject openidobj = JSON.parseObject(oinfoma);
		System.out.println(openidobj);
		String status = (String) openidobj.get("status");// 取出status SUCCESS
		System.out.println(status);
		return status;
	}

	public static String validateBusiness2(Integer systemCode, String companyName, String companyTitle,
			String originalId) throws UnsupportedEncodingException {
		String a = "https://tpay.gack.citic/add_update/company?"+"systemCode=10";
		String b ="&companyName=" + URLEncoder.encode(companyName,"utf-8") + "&companyTitle=" + URLEncoder.encode(companyTitle,"utf-8") + "&originalId=" + URLEncoder.encode(originalId,"utf-8");
		String	oinfoma = HttpGetUtil.httpGet(a+b);
		System.out.println(oinfoma);
		com.alibaba.fastjson.JSONObject openidobj = JSON.parseObject(oinfoma);
		System.out.println(openidobj);
		String status = (String) openidobj.get("status");// 取出status SUCCESS
		System.out.println(status);
		return status;
	}
	
	//店铺详情
	public Map<String, Object> selectByShopinfo(String id){
		
		Map<String, Object>  map=new HashMap<>();
	    String jpql="select new guoanmaker.operator.business.modelnobind.ProvideshopRo(b.businessName, b.companyLogo,b.companyLicenseReplica,b.introduce,"
				+"b.commoditys) from ProvideShop p "
	    		+ "left join p.providerBusiness b where 1=1";
	    jpql+="and p.id='" + id + "' " ;
	    Query query = manager.createQuery(jpql);
		List<ProvideshopRo> result = query.getResultList();
		ProvideshopRo provideshopRo=null;
		if(result.size()>0){
			provideshopRo=result.get(0);
			String str = provideshopRo.getCommoditys();
			if(str!=null&&!str.equals("")){
				String servername = "";
    			List<OperatorServerClass> servers=	selectById(str);
    			if(servers.size()>0&&servers!=null){
    				for (OperatorServerClass operatorServerClass : servers) {
    					servername += operatorServerClass.getServerName()+",";
    				}
    			}
    			if(servers==null){
    				 servername = "";
    			}
    			provideshopRo.setCommoditys(servername);
			}
			 if(provideshopRo.getCompanyCity()!=null&&!provideshopRo.getCompanyCity().equals("")){
				 List<ProvideCity> provideCity=provideCityRepository.findByCode(provideshopRo.getCompanyCity());
				 if(provideCity!=null){
					 provideshopRo.setCompanyCity(provideCity.get(0).getName()); 
				 }
			 }
		}
		map.put("pb", provideshopRo);
	    return map;
	} 
	
public Map<String, Object> selectByShopinfo1(String id){
		
		Map<String, Object>  map=new HashMap<>();
	    String jpql="select new guoanmaker.operator.business.modelnobind.ProvideshopRo(b.businessName, b.companyLogo,b.companyLicenseReplica,b.introduce,"
				+"b.commoditys,b.LicensPhone, b.companyAdress, b.companyProvince, b.companyCity,"+
				"b.companyArea,b.banner,p.cal,b.bannerForPc) from ProvideShop p "
	    		+ "left join p.providerBusiness b where 1=1";
	    jpql+="and b.id='" + id + "' " ;
	    Query query = manager.createQuery(jpql);
		List<ProvideshopRo> result = query.getResultList();
		ProvideshopRo provideshopRo=null;
		if(result.size()>0){
			provideshopRo=result.get(0);
			String str = provideshopRo.getCommoditys();
			if(str!=null&&!str.equals("")){
				String servername = "";
    			List<OperatorServerClass> servers=	selectById(str);
    			if(servers.size()>0&&servers!=null){
    				for (OperatorServerClass operatorServerClass : servers) {
    					servername += operatorServerClass.getServerName()+",";
    				}
    			}
    			if(servers==null){
    				 servername = "";
    			}
    			provideshopRo.setCommoditys(servername);
			}
			 if(provideshopRo.getCompanyCity()!=null&&!provideshopRo.getCompanyCity().equals("")){
				 List<ProvideCity> provideCity=provideCityRepository.findByCode(provideshopRo.getCompanyCity());
				 if(provideCity!=null){
					 provideshopRo.setCompanyCity(provideCity.get(0).getName()); 
				 }
			 }
		}
		map.put("pb", provideshopRo);
	    return map;
	} 
	
	//店铺下的商品列表
	public Map<String, Object> selectByShopforCommditys(String id,String busid, Integer page,
            Integer size){
		Map<String, Object>  map=new HashMap<>();
		String jpql="select new guoanmaker.operator.business.modelnobind.ProvideshopRo(b.businessName, p.companyLogo,p.companyLicenseReplica,p.introduce,"
				+"b.commoditys) from ProvideShop p "
	    		+ "left join p.providerBusiness b where 1=1";
	    jpql+="and p.id='" + id + "' " ;
	    Query query = manager.createQuery(jpql);
		List<ProvideshopRo> result = query.getResultList();
		ProvideshopRo provideshopRo=null;
		if(result.size()>0){
			provideshopRo=result.get(0);
		}
		map.put("proshopinfo", provideshopRo);
	    String jpql1="select new guoanmaker.operator.business.modelnobind.ProvideCommodityRo(c.commodityName, c.synopsis, c.commodityPrice,c.isTerritoryRestriction,c.id,pb.id as busid,c.commodityState,c.commodity_smallimage,c.finalPrice) from  ProvideCommodity c left join"+
	    		    "  c.providerBusiness pb where c.commodityState=2  ";
	    jpql1+=" and pb.id='" + busid + "' " ;
	     Query query1 = manager.createQuery(jpql1);
	     
	     List<ProvideCommodityRo> result2 = query1.getResultList();
		 map.put("total", result2.size());
		 query1.setFirstResult(page*size);
		 query1.setMaxResults(size);
		 List<ProvideCommodityRo> result1 = query1.getResultList();
		for (ProvideCommodityRo provideCommodity : result1) {
			String servercity="";
			//isTerritoryRestriction;//是否有地域限制 1:有 2:没有
			if(provideCommodity.getIsTerritoryRestriction()!=null&&!provideCommodity.getIsTerritoryRestriction().equals("")){
				if(provideCommodity.getIsTerritoryRestriction().equals("2")){
 					 List<OperatorCity> ops=	operatorCityRepository.findAll();
 					 if(ops.size()>0){
 						 for (OperatorCity operatorCity : ops) {
 							 List<ProvideCity>  provideCity1=provideCityRepository.findByCode(operatorCity.getCityId());
 							 if(provideCity1.size()>0){
 								 servercity+=provideCity1.get(0).getName()+",";
 							 }
 						 }
 					 }
				}else if(provideCommodity.getIsTerritoryRestriction().equals("1")){
					List<ProvideCommodityServiceRange>  pcs=provideCommodityServiceRangeRepository.selectByServerArea(provideCommodity.getId());
					    if(pcs.size()>0){
						 for (ProvideCommodityServiceRange provideCommodityServiceRange : pcs) {
							 ProvideCity  city=	 provideCityRepository.findOne(provideCommodityServiceRange.getCity().getId());
							 servercity+=city.getName()+",";
						}
					 }
				}
			}
			String c=removeSameString(servercity);
			provideCommodity.setServiceCity(c);
		}
		map.put("commoditys", result1);
		return  map;
	}
	
	/** 
	 * 去掉重复字符串 
	 * @param str 
	 * @return String  
	 * */  
	public static  String removeSameString(String str){    
	    Set<String> mLinkedSet = new LinkedHashSet<String>();    
	    String[] strArray = str.split(",");    
	    StringBuffer sb = new StringBuffer();    
	    for (int i = 0; i < strArray.length; i++)    
	    {    
	        if (!mLinkedSet.contains(strArray[i]))    
	        {    
	            mLinkedSet.add(strArray[i]);    
	            sb.append(strArray[i] + " ");    
	        }else{  
	  //          System.out.println("重复字符:"+strArray[i]);  
	        }    
	    }    
//	    System.out.println(mLinkedSet);    
	    return sb.toString().substring(0, sb.toString().length() - 1);    
	}   
	
	
	
	//店铺的资料变更 审核列表
	public Map<String, Object> pendingStoreList(Integer page, Integer size, Integer status) {
		Map<String,Object>  map=new HashMap<>();
		if(status!=null){
			if(status==0){
				String jpql=" select new guoanmaker.operator.business.modelnobind.ShopInfosAudit(b.busNumber, b.businessName, b.commoditys, u.username,p.stateTime,"
					     + "p.acceptTime, p.refuseTime,p.state,p.id as storeid,b.id as busid) from  ProviderBusiness b "
						+ "left join b.provideShop  p left join  b.personalUser u  where 1=1"
						+ " and u.isProvider='2'";
					    //0待审核 1审核成功  2审核失败   3冻结
						jpql+=" and p.state=0";
				        jpql+=" order by  p.stateTime desc";
						 if(page==null){
								page=0;
							}
							if (size==null) {
								size=10;
							}
							Query query = manager.createQuery(jpql);
							List<ShopInfosAudit> result = query.getResultList();
							map.put("totle", result.size());
							query.setFirstResult(page*size);
							query.setMaxResults(size);
							List<ShopInfosAudit> result1 = query.getResultList();
							if(result1.size()>0){
								for (ShopInfosAudit providerBusiness : result1) {
									// 业务类别
									String str = providerBusiness.getCommoditys();
									if(str!=null&&!str.equals("")){
										String servername = "";
						    			List<OperatorServerClass> servers=	selectById(str);
						    			if(servers.size()>0&&servers!=null){
						    				for (OperatorServerClass operatorServerClass : servers) {
						    					servername += operatorServerClass.getServerName()+",";
						    				}
						    			}
						    			if(servers==null){
						    				 servername = "";
						    			}
										providerBusiness.setCommoditys(servername);
									}
								}
							}
							map.put("result", result1);	
		     	}else{
						String jpql="select  s from  OperatorStoredataChange s where 1=1";
						 if(status==1){
							jpql+=" and s.state=1";
							jpql+=" order by  s.acceptTime desc";
						}else if(status==2){
							jpql+=" and s.state=2";
							jpql+=" order by  s.refuseTime desc";
						}
						 if(page==null){
								page=0;
							}
							if (size==null) {
								size=10;
							}
							Query query = manager.createQuery(jpql);
							List<OperatorStoredataChange> result = query.getResultList();
							map.put("totle", result.size());
							query.setFirstResult(page*size);
							query.setMaxResults(size);
							List<OperatorStoredataChange> result1 = query.getResultList();
							if(result1.size()>0){
								for (OperatorStoredataChange providerBusiness : result1) {
									// 业务类别
									String str = providerBusiness.getCommoditys();
									if(str!=null&&!str.equals("")){
										String servername = "";
						    			List<OperatorServerClass> servers=	selectById(str);
						    			if(servers.size()>0&&servers!=null){
						    				for (OperatorServerClass operatorServerClass : servers) {
						    					servername += operatorServerClass.getServerName()+",";
						    				}
						    			}
						    			if(servers==null){
						    				 servername = "";
						    			}
										providerBusiness.setCommoditys(servername);
									}
								}
							}
							map.put("result", result1);	 
			  }
		}
		return  map;
}
	
	@Transactional
	public ReturnResult auditStoreinfo(String busid,String storeid,String userid) throws UnsupportedEncodingException{
		ReturnResult  returnResult=new ReturnResult();
			ProvideShop provideShop=	provideShopRepository.findOne(storeid);
			if(provideShop!=null){
				//0待审核 1审核成功  2审核失败   3冻结
				provideShop.setState(1);
				provideShop.setAcceptTime(new Date());
				provideShopRepository.saveAndFlush(provideShop);
				//店铺资料更换到商户
				ProviderBusiness providerBusiness=	providerBusinessRepository.findOne(busid);
				if(providerBusiness!=null){
					providerBusiness.setBusinessName(provideShop.getBusinessName());
					providerBusiness.setCompanyAdress(provideShop.getCompanyAdress());
					providerBusiness.setCompanyArea(provideShop.getCompanyArea());
					providerBusiness.setCompanyCity(provideShop.getCompanyCity());
					providerBusiness.setCompanyLicenseReplica(provideShop.getCompanyLicenseReplica());
					providerBusiness.setCompanyLogo(provideShop.getCompanyLogo());
					providerBusiness.setCompanyProvince(provideShop.getCompanyProvince());
					providerBusiness.setLicensPhone(provideShop.getLicensPhone());
					providerBusiness.setIntroduce(provideShop.getIntroduce());
					providerBusiness.setBanner(provideShop.getBanner());
					providerBusiness.setBannerForPc(provideShop.getBannerForPc());
					ProviderBusiness  pb=	providerBusinessRepository.saveAndFlush(providerBusiness);
					if((pb.getCompanyName()!=null&&!pb.getCompanyName().equals(""))
							||(pb.getBusinessName()!=null&&!pb.getBusinessName().equals(""))){
						// 平台描述为10
						String flag = validateBusiness2(10, pb.getBusinessName(),
								pb.getCompanyName(), busid);
						if (flag.equals("SUCCESS")) {
							System.out.println("编辑成功");
						}
					}
					MessageType messageType=new MessageType();
					messageType.setSourceid(storeid);
					messageType.setCreatedate(new Date());
					messageType.setDecribestr("您有一个【"+providerBusiness.getBusinessName()+"】店铺资料审核通过");
					messageType.setIsread(0);
					messageType.setType(8);
					messageType.setBusinessid(busid);
					messageTypeRepository.save(messageType);
					//审批通过
					OperatorStoredataChange  operatorStoredataChange=new OperatorStoredataChange();
					operatorStoredataChange.setBusinessName(pb.getBusinessName());
					operatorStoredataChange.setCommoditys(pb.getCommoditys());
					operatorStoredataChange.setAcceptTime(new Date());
					operatorStoredataChange.setBusid(busid);
					operatorStoredataChange.setState(1);
					operatorStoredataChange.setStateTime(provideShop.getStateTime());
					operatorStoredataChange.setStoreid(storeid);
					OperatorUser operatorUser = operatorUserRepository.findOne(userid);
					if (operatorUser != null) {
						operatorStoredataChange.setUseraccountforcord(operatorUser.getUsername() + "已审批");
					}
					operatorStoredataChange.setUsername(providerBusiness.getPersonalUser().getUsername());
					operatorStoredataChange.setCompanyAdress(pb.getCompanyAdress());
					operatorStoredataChange.setCompanyArea(pb.getCompanyArea());
					operatorStoredataChange.setCompanyCity(pb.getCompanyCity());
					operatorStoredataChange.setCompanyLicenseReplica(pb.getCompanyLicenseReplica());
					operatorStoredataChange.setCompanyLogo(pb.getCompanyLogo());
					operatorStoredataChange.setCompanyProvince(pb.getCompanyProvince());
					operatorStoredataChange.setLicensPhone(pb.getLicensPhone());
					operatorStoredataChange.setIntroduce(pb.getIntroduce());
					operatorStoredataChange.setBanner(pb.getBanner());
					operatorStoredataChange.setBannerForPc(pb.getBannerForPc());
					operatorStoredataChange.setCal(provideShop.getCal());
					operatorStoredataChangeRepository.save(operatorStoredataChange);
					
			 }
			//审批记录
				/*OperatorRefuseRecord operatorRefuseRecord = new OperatorRefuseRecord();
				operatorRefuseRecord.setAttributId(storeid);
				operatorRefuseRecord.setStatus(1);
				operatorRefuseRecord.setOpchannel(5);
				operatorRefuseRecord.setRefuseTime(new Date());
				OperatorUser operatorUser = operatorUserRepository.findOne(userid);
				if (operatorUser != null) {
					operatorRefuseRecord.setUseraccountforcord(operatorUser.getUsername() + "已审批");
				}
				operatorRefuseRecordRepository.save(operatorRefuseRecord);*/
				returnResult.setKey("success");
				returnResult.setValue("审核成功");
		}else{
			returnResult.setKey("error");
			returnResult.setValue("审核失败");
		}
		return   returnResult;
	}
	
	
   /**
    * 拒绝店铺资料
    * @param storeid
    * @return
    */
	@Transactional
	public ReturnResult refuseStoreinfo(String storeid,String userid,String reasonName,String content){
		ReturnResult  returnResult=new ReturnResult();
		ProvideShop provideShop=	provideShopRepository.findOne(storeid);
		if(provideShop!=null){
			//0待审核 1审核成功  2审核失败   3冻结
			provideShop.setState(2);
			provideShop.setRefuseTime(new Date());
			provideShopRepository.saveAndFlush(provideShop);
			/*OperatorRefuseRecord operatorRefuseRecord = new OperatorRefuseRecord();
			operatorRefuseRecord.setAttributId(storeid);
			operatorRefuseRecord.setStatus(2);
			operatorRefuseRecord.setOpchannel(5);
			operatorRefuseRecord.setReasonName(reasonName);
			operatorRefuseRecord.setContent(content);
			operatorRefuseRecord.setRefuseTime(new Date());
			OperatorUser operatorUser = operatorUserRepository.findOne(userid);
			if (operatorUser != null) {
				operatorRefuseRecord.setUseraccountforcord(operatorUser.getUsername() + "已拒绝");
			}
			operatorRefuseRecordRepository.save(operatorRefuseRecord);*/
			//审批拒绝
			OperatorStoredataChange  operatorStoredataChange=new OperatorStoredataChange();
			operatorStoredataChange.setBusinessName(provideShop.getBusinessName());
			operatorStoredataChange.setRefuseTime(new Date());
			operatorStoredataChange.setBusid(provideShop.getProviderBusiness().getId());
			operatorStoredataChange.setState(2);
			operatorStoredataChange.setStateTime(provideShop.getStateTime());
			operatorStoredataChange.setStoreid(storeid);
			OperatorUser operatorUser = operatorUserRepository.findOne(userid);
			if (operatorUser != null) {
				operatorStoredataChange.setUseraccountforcord(operatorUser.getUsername() + "已拒绝");
			}
			operatorStoredataChange.setCommoditys(provideShop.getProviderBusiness().getCommoditys());
			operatorStoredataChange.setUsername(provideShop.getProviderBusiness().getPersonalUser().getUsername());
			operatorStoredataChange.setReasonName(reasonName);
			operatorStoredataChange.setContent(content);
			operatorStoredataChange.setCompanyAdress(provideShop.getCompanyAdress());
			operatorStoredataChange.setCompanyArea(provideShop.getCompanyArea());
			operatorStoredataChange.setCompanyCity(provideShop.getCompanyCity());
			operatorStoredataChange.setCompanyLicenseReplica(provideShop.getCompanyLicenseReplica());
			operatorStoredataChange.setCompanyLogo(provideShop.getCompanyLogo());
			operatorStoredataChange.setCompanyProvince(provideShop.getCompanyProvince());
			operatorStoredataChange.setLicensPhone(provideShop.getLicensPhone());
			operatorStoredataChange.setIntroduce(provideShop.getIntroduce());
			operatorStoredataChange.setBanner(provideShop.getBanner());
			operatorStoredataChange.setBannerForPc(provideShop.getBannerForPc());
			operatorStoredataChange.setCal(provideShop.getCal());
			operatorStoredataChangeRepository.save(operatorStoredataChange);
			
			MessageType messageType=new MessageType();
			messageType.setSourceid(storeid);
			messageType.setCreatedate(new Date());
			messageType.setDecribestr("您有一个【"+provideShop.getProviderBusiness().getBusinessName()+"】店铺资料审核未通过");
			messageType.setIsread(0);
			messageType.setType(8);
			messageType.setBusinessid(provideShop.getProviderBusiness().getId());
			messageTypeRepository.save(messageType);
			
			returnResult.setKey("success");
			returnResult.setValue("操作成功");
		}else{
			returnResult.setKey("error");
			returnResult.setValue("操作失败");
		}
		return   returnResult;
	}
	
	/**
	 * 店铺资料变更详情
	 * 
	 */
	public  Map<String, Object>     storeinfos(String busid,String storeid,String sid){
		Map<String, Object> map=new HashMap<>();
		if(sid==null||sid.equals("")){
			//变更前
			String jpql1="select new guoanmaker.operator.business.modelnobind.BusinessRo"
					+ "(b.businessName,b.LicensPhone,b.companyAdress,b.companyProvince,"+
					"b.companyCity, b.companyArea, b.companyLogo,b.companyLicenseReplica,"+
					"b.companyIntroduce,b.introduce) from ProviderBusiness b   where  b.id='" + busid + "' ";
			Query query1 = manager.createQuery(jpql1);
			List<BusinessRo> result1 = query1.getResultList();
			BusinessRo businessRo=null;
			if(result1.size()>0){
				businessRo=result1.get(0);
				
			}
			map.put("businessinfo", businessRo);
			//变更后
			String jpql="select new guoanmaker.operator.business.modelnobind.ProvideshopRo(p.businessName, p.companyLogo,p.companyLicenseReplica,p.introduce,"
					+"b.commoditys,p.licensPhone, p.companyAdress, p.companyProvince, p.companyCity,"+
					"p.companyArea,p.banner,p.cal,p.bannerForPc) from ProvideShop p "
					+ "left join p.providerBusiness b where 1=1";
			jpql+="and p.id='" + storeid + "' " ;
			Query query = manager.createQuery(jpql);
			List<ProvideshopRo> result = query.getResultList();
			ProvideshopRo provideshopRo=null;
			if(result.size()>0){
				provideshopRo=result.get(0);
				
			}
			map.put("storeinfo", provideshopRo);
			List<OperatorRefuseRecord> records=	operatorRefuseRecordRepository.selectBystoreInfo(storeid);
			map.put("records", records);
		}else{
			OperatorStoredataChange  oo=operatorStoredataChangeRepository.findOne(sid);
			if(oo!=null){
				map.put("storeinfo", oo);
			}
		}
		return  map;
	}
	
	
	
	
	
}
